import { constantRoutes } from '@/router'
import { findNavTree } from '@/http/moudules/menu'
import Layout from '@/layout'
import { findPermissions } from '@/http/moudules/user'

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    // console.log('tmp.component', tmp.component)
    const component = () => import(`@/views${tmp.component}.vue`)
    const router = {
      path: tmp.url,
      component: tmp.component ? component : Layout,
      hidden: !tmp.hidden,
      name: tmp.name,
      meta: { title: tmp.title, icon: tmp.icon }
    }
    if (tmp.children) {
      router.children = filterAsyncRoutes(tmp.children)
    }
    res.push(router)
  })
  return res
}

const state = {
  routes: [],
  addRoutes: [],
  permission: []

}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_PERMISSION: (state, permission) => {
    state.permission = permission
  }
}

const actions = {
  generateRoutes({ commit, dispatch }) {
    return new Promise(async(resolve) => {
      // const accessedRoutes = asyncRoutes || []
      const router = await dispatch('getTree')
      const permission = await dispatch('getPermission')
      const accessedRoutes = filterAsyncRoutes(router)
      console.log(accessedRoutes)
      commit('SET_ROUTES', accessedRoutes)
      commit('SET_PERMISSION', permission)
      resolve(accessedRoutes)
    })
  },
  getTree() {
    return new Promise(resolve => {
      findNavTree({ 'userName': localStorage.getItem('user') }).then(res => {
        if (res.code === 200) {
          resolve(res.data)
        } else {
          resolve([])
        }
      })
    })
  },
  getPermission() {
    return new Promise(resolve => {
      findPermissions({ 'name': localStorage.getItem('user') }).then(res => {
        if (res && res.code === 200) {
          resolve(res.data)
        } else {
          resolve([])
        }
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
